package com.wjw.utils.database;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wjw.utils.CMDUtil;
import com.wjw.utils.FileUtil;

/**
 * @desc mysql数据库备份 * web服务器跟数据库同一台机器时有效
 * @author wjw
 * @date 2016年11月22日下午2:39:34
 */
public class MysqlCMD {
	
    /**
     * 日志对象
     */
    protected static Logger log = LoggerFactory.getLogger(MysqlCMD.class);
    
	/**
	 * mysql数据备份
	 */
	private String username;//数据库用户名
	private String password;//数据库密码
	private String mysqldumpPath;//mysqldump程序目录
	private String host;// 备份主机
	private String backupPath;// 备份目录
	private boolean isBackup; //是否备份到本地
	private String database; //数据库名称
	
	public MysqlCMD(String username,String password,String mysqldumpPath,String host,String backupPath,boolean isBackup,String database) {
		this.username=username;
		this.password=password;
		this.mysqldumpPath=mysqldumpPath;
		this.host=host;
		this.backupPath=backupPath;
		this.isBackup=isBackup;
		this.database=database;
	}
	
	
	/** 备份 *  */
	public void backup() {
		if(isBackup){
			log.info("开始备份......");
			FileUtil.createFatherFolder(backupPath);//创建备份目录
			String backFileName=database+new SimpleDateFormat("yyyy-MM-ddHHmmssSSS").format(new Date())+".sql";
			StringBuilder sbu =new StringBuilder();
			sbu.append(mysqldumpPath);
			sbu.append("mysqldump ");  
			sbu.append(" --add-drop-table");
			sbu.append(" -h"+host);
			sbu.append(" -u"+username);
			sbu.append(" -p"+password);
			sbu.append(" "+database);
			sbu.append(" >");
			sbu.append(" "+backupPath + File.separator + backFileName);
			log.info("执行cmd命令:"+sbu.toString());
			CMDUtil.executeCmdFlash(sbu.toString());
			log.info("备份结束......");
		}
	}

	/** sql文件导入  */
	public void load(String filename) {
		String filepath = "" + filename;
		String stmt1="mysqladmin -u "+username+" -p"+password+" create finacing";
		String stmt2="mysql -u "+username+" -p"+password+" finacing < "+filepath;
		String[] cmd={ "cmd", "/c", stmt2 };
		try {
			Runtime.getRuntime().exec(stmt1);
			Runtime.getRuntime().exec(cmd);
			System.out.println("数据已从 " + filepath + " 导入到数据库中");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
}